<template>
    <view class="page_root" data-page-name="auth" data-page-identification="b_j9st1n6175">
        <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    </view>
</template>
<script setup>
    import {
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated,
        getCurrentInstance
    } from 'vue'
    import { useRoute } from 'vue-router'
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        traversalTreeStructure,
        set,
        checkCaseCondition,
        throttle,
        merge,
        debounce,
        getGridStyle,
        getCellRenderAble,
        formulaStrategy,
        getApplicationId
    } from '@/utils/index'
    import { isEqual, isNullOrEmpty, isEmptyArr, isArray, isEmpty, isNullOrUnDef, isContained } from '@/utils/is'
    import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart'
    import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate } from '@/utils/format'
    import { FormFormat } from '@/utils/formFormat'
    import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark'
    import dayjs from 'dayjs'
    import hashSum from 'hash-sum'
    /*** UNI_APP_EXEGESIS ***
 import { handleRedirect, permission, parseJson } from '@/utils/common';
 import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
 import { BroadcastMessage } from '@/utils/BroadcastMessage';
 import { sendToken } from "@/hooks/useIframeToken";
 *** UNI_APP_EXEGESIS ***/

    // ---------------------------- 属性定义 ----------------------------
    const sourceId = 'page50001883'

    // 是否显示菜单按钮
    const isMenuIconShow = false
    // NAVIGATION_MENU
    const handleShowNavigation = () => {}

    let isProcessState = ref(false)

    const setTimeOutList = []

    // ============================ 属性定义 ============================

    // ---------------------------- 元素数据引用 ----------------------------
    // 动态key的map
    const fieldTypeMap = {}
    // 动态key的map
    const refMap = {}

    const showState = reactive({})
    // ============================ 元素数据引用 ============================

    // ---------------------------- 数据 ----------------------------

    // ============================ 数据 ============================

    // ---------------------------- 方法 ----------------------------
    // ---------------------------- 页面数据 ----------------------------

    // ============================ 页面数据 ============================

    // ---------------------------- 响应 ----------------------------

    // ============================ 响应 ============================

    // ---------------------------- 函数 ----------------------------

    // 自定义函数 返回上一页
    const customFunction_goBack_k4z93223fy = (...params) => {
        uni.navigateBack()
    }

    // ============================ 函数 ============================

    // ---------------------------- 页面参数 ----------------------------

    const pageParameter_state = reactive({
        'processInstanceId': undefined
    })

    // ============================ 页面参数 ============================

    // ---------------------------- 组件事件处理方法 ----------------------------

    // ============================ 组件事件处理方法 ============================

    // ============================ 方法 ============================

    // ---------------------------- 生命周期 ----------------------------
    /*** UNI_APP_EXEGESIS ***
 // 获取上一层传递的数据
 const workflowChannel = new BroadcastMessage('WORKFLOW');
 workflowChannel.publish({ status: 'Ready' });
 workflowChannel.subscribe((data) => {
 if (data) {
 isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
 }
 });
 *** UNI_APP_EXEGESIS ***/

    const pageScrollTop = ref(0)

    // *** PREVIEW_EXEGESIS ***
    onMounted(() => {
        setPageParams(route.query)
        // 设置表单的rule
        try {
        } catch {
            // do nothing
        }
    })
    // *** PREVIEW_EXEGESIS *** //

    /*** UNI_APP_EXEGESIS ***
 const routeOption = ref({})
 onLoad((option) => {
 routeOption.value = option;
 });
 onReady(() => {
 setPageParams(routeOption.value)
 // 设置表单的rule
 try{

 }catch{
 // do nothing
 }
 });
 // 图表刷新标记
 const uChartsReshowFlag = ref(false);
 onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
 uChartsReshowFlag.value = false
 })
 onShow(() => {
 uChartsReshowFlag.value = true; // 页面激活后,标记置为true

 setPageParams(routeOption.value)
 })
 onPageScroll(e => {
 pageScrollTop.value = e.scrollTop
 });
 *** UNI_APP_EXEGESIS ***/

    const setPageParams = routerParam => {
        const pageParams = [{ 'dataType': 'STRING', 'dependencies': [], 'name': 'processInstanceId' }]
        const strategyMap = {
            STRING: (param, paramValue) => {
                pageParameter_state[param.name] = paramValue
            },
            BOOLEAN: (param, paramValue) => {
                if ('true' === (paramValue || '').toLowerCase()) {
                    pageParameter_state[param.name] = true
                } else if ('false' === (paramValue || '').toLowerCase()) {
                    pageParameter_state[param.name] = false
                } else {
                    // TODO: 是否要支持toast
                    console.error('参数传入错误！类型不匹配！')
                }
            },
            NUMBER: (param, paramValue) => {
                if (!isNaN(paramValue)) {
                    pageParameter_state[param.name] = Number(paramValue)
                } else {
                    // TODO: 是否要支持toast
                    console.error('参数传入错误！类型不匹配！')
                }
            },
            ARRAY: (param, paramValue) => {
                if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
                    // default value
                    pageParameter_state[param.name] = []
                } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
                    try {
                        pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue))
                    } catch (error) {
                        console.error('参数解析失败 ', error)
                    }
                } else {
                    console.error('参数传入错误！类型不匹配！')
                }
            }
        }
        pageParams.forEach(param => {
            strategyMap[param.dataType](param, routerParam[param.name])
        })
    }

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /*** UNI_APP_EXEGESIS ***
 onPullDownRefresh(() => {
 // 下拉刷新
 setTimeout(() => {
 uni.stopPullDownRefresh()
 }, 1000)
 })
 *** UNI_APP_EXEGESIS ***/

    // ============================ 生命周期 ============================

    // ---------------------------- 数据关联处理 ----------------------------
    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================
    //
    // ============================ 数据关联处理 ============================

    // ---------------------- 不同组件自定义的处理逻辑 ---------------------

    // ====================== 不同组件自定义的处理逻辑 ======================

    // ================================定制化逻辑========================================
    const stateForm = reactive({
        tenantId: null,
        sessionKey: null,
        userId: null,
        mobile: null,
        productId: null,
        getTidUrl: null,
        newUrl: null
    })
    var currentURL = window.location.href

    function getParameterByName(name, url = window.location.href) {
        name = name.replace(/[\[\]]/g, '\\$&')
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url)
        if (!results) return null
        if (!results[2]) return ''
        return decodeURIComponent(results[2].replace(/\+/g, ' '))
    }

    stateForm.sessionKey = getParameterByName('sessionKey', currentURL)
    stateForm.userId = getParameterByName('userId', currentURL)
    stateForm.mobile = getParameterByName('mobile', currentURL)
    async function getTenantId() {
        try {
            let firstSlashIndex = stateForm.newUrl.indexOf('/', 8)
            let prefix

            if (firstSlashIndex !== -1) {
                prefix = stateForm.newUrl.substring(0, firstSlashIndex)
                let protocols = ['http://', 'https://']
                let protocol = protocols.find(p => prefix.includes(p))

                if (protocol) {
                    let result = prefix.substring(protocol.length)
                    // result = result + '/app_50000005/';
                    console.log(result, 'result')
                    let data = await post(`/base/api/v1/product/url`, {
                        url: result
                    })
                    if (data.status === 'success') {
                        stateForm.tenantId = data.data.tenantId
                        stateForm.productId = data.data.id
                        console.log(stateForm.tenantId, 'stateForm.tenantId')
                        getUser()
                    } else {
                        console.error('获取tenantId失败')
                    }
                } else {
                    console.error('未找到 `http://` 或 `https://`')
                }
            } else {
                console.error('无法提取前缀')
            }
        } catch (error) {
            console.error('getTenant1Id出现错误:', error)
        }
    }

    function getUser() {
        try {
            // let localStorageData = localStorage.getItem('app-user-store');
            let localStorageDataDP = localStorage.getItem('app-user')
            // debugger
            if (localStorageDataDP !== null) {
                localStorageDataDP = JSON.parse(localStorageDataDP)
                if (localStorageDataDP.token !== null) {
                    console.log('有token调接口校验token的可行性')
                    checkToken(localStorageDataDP.token, localStorageDataDP.uuid)
                } else {
                    console.log('这里是没有token走的调登录')
                    getToken()
                }
            } else {
                getToken()
            }
        } catch (error) {
            console.error('getUser出现错误:', error)
        }
    }
    async function checkToken(token, uuid) {
        try {
            let params = {
                uuid: uuid,
                token: token,
                appId: 'app_preview'
            }
            let result = await post('/base/api/v1/valid', params)
            if (result.data === null) {
                // 如果data为null，则执行getToken操作
                getToken()
            } else {
                // 如果data不为null，则执行getNe1wUrl操作
                let newUserData = {
                    uuid: uuid,
                    token: token,
                    productId: stateForm.productId,
                    tenantId: stateForm.tenantId,
                    appid: 'app_preview'
                }
                localStorage.setItem('app-user', JSON.stringify(newUserData))
                localStorage.setItem('app-user-store', JSON.stringify(newUserData))
                console.log('执行')
                console.log(localStorage.getItem('app-user-store'))
                window.location.href = stateForm.getTidUrl
            }
        } catch (error) {
            getToken()
            console.error('checkToken出现错误:', error)
        }
    }
    async function getToken() {
        try {
            let uuid = ''
            let token = ''
            const params = {
                sessionKey: stateForm.sessionKey,
                mobile: stateForm.mobile,
                appId: 'app_preview',
                withTenantIdFlag: false,
                mobileIsUserName: false,
                tenantId: stateForm.tenantId
            }
            let result = await post('/base/api/v1/open/login', params)
            console.log(result.status, 'getTokenstatus')
            if (result.data) {
                console.log(result, '登陆接口返回')
                uuid = result.data.uuid
                token = result.data.token
                let newUserData = {
                    uuid: uuid,
                    token: token,
                    productId: stateForm.productId,
                    tenantId: stateForm.tenantId,
                    appid: 'app_preview'
                }
                localStorage.setItem('app-user-store', JSON.stringify(newUserData))
                localStorage.setItem('app-user', JSON.stringify(newUserData))
                console.log('执行')
                console.log(localStorage.getItem('app-user-store'))
                window.location.href = stateForm.getTidUrl
            } else {
                uni.showToast({
                    title: '非法账号',
                    icon: 'error'
                })
            }
        } catch (error) {
            console.error('getToken出现错误:', error)
            uni.showToast({
                title: '非法账号',
                icon: 'error'
            })
        }
    }

    async function getNewUrl() {
        try {
            const response = await post(
                '/solution-ppm/api/v2/built-in-system-ppm/wechat_auth_config/query/user_address',
                {
                    userId: stateForm.userId
                }
            )
            const result = response.data // 获取响应数据
            console.log(result, '跳转地址')
            if (result.productUri) {
                stateForm.getTidUrl = result.appUri
                stateForm.newUrl = result.productUri
                getTenantId()
            }
        } catch (error) {
            // 请求失败时调用 getToken
            getToken()

            // 这里处理请求错误
            console.log('getNewUrl出现错误:', error)
        }
    }
    // 清除 app-user-store 的数据
    onMounted(() => {
        localStorage.removeItem('app-user-store')
        console.log('清除')
        console.log(localStorage.getItem('app-user-store'))
    })
    getNewUrl()
</script>
<style lang="less" scoped>
    .page_root {
        min-height: 100%;
        box-sizing: border-box;
    }
</style>
